package ru.slovoslovo.cropmotion.ui.filetree;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import org.eclipse.swt.graphics.Image;

/**
 * Default or adapter implementation for ITreeNode
 * 
 * @author ppavlov
 *
 */
public class FileTreeNode {
    private File file = null;
    
    protected FileTreeNode parent = null;
    protected List<FileTreeNode> childrens = null;

    public FileTreeNode(FileTreeNode parent) {
        this.parent = parent;
    }

    public Image getImage() {
        return null;
    }

    public FileTreeNode getParent() {
        return parent;
    }

    public File getFile() {
        return file;
    }

    public void setFile(File file) {
        this.file = file;
    }

    public FileTreeNode(FileTreeNode parent, File file) {
        this.parent = parent;
        setFile(file);
    }

    public String getName() {
        StringBuilder sb = new StringBuilder();
        
        if (getFile() != null){
            sb.append(getFile().getName().isEmpty() ? getFile().getPath() : getFile().getName());
            if (getFile().isDirectory()){
                sb.insert(0, '[').append(']');
            }
        }

        return sb.toString();
    }

    public List<FileTreeNode> getChildrens() {
        if (childrens == null){
            childrens = new ArrayList<FileTreeNode>();
            File[] childFiles = (getFile() != null) ? getFile().listFiles() : File.listRoots();
            
            if (childFiles != null){
                for (File file : childFiles){
                    childrens.add(new FileTreeNode(this, file));
                }
            }
        }
        return childrens;
    }

    public boolean hasChildren() {
        return getChildrens().size() > 0;
    }
    
}
